package com.pabble.webnative;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Base64;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Bridge {
    private Activity mContext;
    private WebView mWebView;
    public final static int PHOTO_REQUEST = 100;
    public final static int PERMISSION_REQUEST = 101;
    public final static int CAMERA_REQUEST = 102;

    private final int invalidHandlerId = -1;

    private Accelerometer mAccelerometer;

    private boolean accelerometerOpen = false;


    Bridge(Activity ctx, WebView view){
        mContext = ctx;
        mWebView = view;
    }

    public Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    public void evaluateJavascript(String js, ValueCallback vcb){
        mWebView.evaluateJavascript(js,vcb);
    }

    public void callJavascript(String method, String params){
        callJavascript(method,params,invalidHandlerId);
    }

    public void callJavascript(String method, String params, int id){
        String p = params!=null?params:"";
        final String js = String.format("OnCall('%s','%s')",method,p);
        mContext.runOnUiThread(()->{
            mWebView.evaluateJavascript(js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    if (id != invalidHandlerId){
                        Message msg = new Message();
                        msg.what = id;
                        msg.obj = value;
                        mHandler.handleMessage(msg);
                    }
                }
            });
        });
    }

    public void takePhoto(String title) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        alertDialog.setTitle(title);
        alertDialog.setItems(new CharSequence[]{"相机", "相册"},
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
                        Uri imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            imageUri = FileProvider.getUriForFile(mContext, "com.example.baidulist.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                        }else {
                            imageUri = Uri.fromFile(fileUri);
                        }
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                        mContext.startActivityForResult(intent,PHOTO_REQUEST);
                    } else {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_PICK);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        mContext.startActivityForResult(intent, PHOTO_REQUEST);
                    }
                }
            });
        alertDialog.show();
    }

    public String checkPermission(String str){
        String [] array = str.split(",");

        String need = "";
        for(int i=0; i<array.length; i++){
            if (ContextCompat.checkSelfPermission(mContext, array[i]) != PackageManager.PERMISSION_GRANTED) {
                if(need.length() > 0){
                    need+=",";
                }
                need+=array[i];
            }
        }
        return  need;
    }

    public void applyPermission(String str){
        String [] array = str.split(",");

        List<String> permissionList = new ArrayList<>();

        for(int i=0; i<array.length; i++){
            if (ContextCompat.checkSelfPermission(mContext, array[i])
                    != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(array[i]);
            }
        }
        if (permissionList.isEmpty()) {
            callJavascript("permission","1");
        } else {
            ActivityCompat.requestPermissions(mContext,permissionList.toArray(new String[permissionList.size()]), PERMISSION_REQUEST);
        }
    }

    public void saveImageToBase64(Bitmap bitmap1){
        new Thread(()->{
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap1.compress(Bitmap.CompressFormat.PNG,50,stream);
            String sImage = Base64.encodeToString(stream.toByteArray(),Base64.DEFAULT);
            String newPath = mContext.getFilesDir().getAbsolutePath()+"/select_temp.txt";
            File f = new File(newPath);
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(f);
                out.write(sImage.getBytes());
                out.flush();
                out.close();
                callJavascript("takephoto","1,"+newPath);
            } catch (IOException e) {
                callJavascript("takephoto","0");
            }
        }).start();
    }

    public void openAccelerometer(int periodUs){
        if(accelerometerOpen == false){
            if(mAccelerometer == null){
                mAccelerometer = new Accelerometer(mContext,periodUs);
            }
            mAccelerometer.enable();
        }
        accelerometerOpen = true;
    }
    public void closeAccelerometer(){
        if(accelerometerOpen){
            mAccelerometer.disable();
        }
        accelerometerOpen = false;
    }

}
